import formInfo from '@ohos.app.form.formInfo';
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formProvider from '@ohos.app.form.formProvider';
import { ApiManager, City, DataUtils, PreferenceManager, RdbManager, WeatherRealTime } from '@ohos/nmc';

export default class EntryFormAbility extends FormExtensionAbility {

  lastRefreshTime: string = "";
  localCity: City = null
  realTimeWeather: WeatherRealTime = null

  onAddForm(want) {
    // Called to return a FormBindingData object.
    let formData = {};
    return formBindingData.createFormBindingData(formData);
  }

  onCastToNormalForm(formId) {
    // Called when the form provider is notified that a temporary form is successfully
    // converted to a normal form.
  }

  onUpdateForm(formId) {
    // Called to notify the form provider to update a specified form.
  }

  onChangeFormVisibility(newStatus) {
    // Called when the form provider receives form events from the system.
  }

  onFormEvent(formId, message) {
    // Called when a specified message event defined by the form provider is triggered.
    console.info(`FormAbility onEvent, formId = ${formId}, message: ${JSON.stringify(message)}`);

    // this.readWeatherData().then(()=>{
    //   let formData = {
    //     'title': 'Title Update Success.', // 和卡片布局中对应
    //     'detail': 'Detail Update Success.', // 和卡片布局中对应
    //   };
    //   let formInfo = formBindingData.createFormBindingData(formData)
    //   formProvider.updateForm(formId, formInfo).then((data) => {
    //     console.info('FormAbility updateForm success.' + JSON.stringify(data));
    //   }).catch((error) => {
    //     console.error('FormAbility updateForm failed: ' + JSON.stringify(error));
    //   })
    // })
  }

  onRemoveForm(formId) {
    // Called to notify the form provider that a specified form has been destroyed.
  }

  onAcquireFormState(want) {
    // Called to return a {@link FormState} object.
    return formInfo.FormState.READY;
  }

  readWeatherData(): Promise<any> {
    return PreferenceManager.getInstance().getLastRequestTime()
      .then(lastRefreshTime => {
        this.lastRefreshTime = new Date(lastRefreshTime).toTimeString();
        PreferenceManager.getInstance().getCacheValidTime()
          .then(cacheValidTime => {
            const loopRefresher = (useCache?: boolean) => {
              ApiManager.getInstance().getCurrentLocation()
                .then(location => {
                  this.localCity = location;
                  ApiManager.getInstance().qLookupCity(DataUtils.getCitySearchIdentity(this.localCity))
                    .then(info => {
                      // 矫正缓存的城市信息
                      this.localCity.name = info[0].name;
                      this.localCity.adm1 = info[0].adm1;
                      this.localCity.adm2 = info[0].adm2;
                      if (!useCache) {
                        // 各城市气象警告
                        ApiManager.getInstance()
                          .qGetWeatherRealTime(DataUtils.getCitySearchIdentity(this.localCity))
                          .then(realTimeWeather => {
                            this.realTimeWeather = realTimeWeather;
                          })
                      } else {
                        RdbManager.getInstance()
                          .getCache(DataUtils.getCitySearchIdentity(this.localCity))
                          .then(cache => {
                            this.realTimeWeather = cache.realtime;
                          })
                      }
                    })
                })
            }
            if (!(new Date().getTime() - lastRefreshTime > cacheValidTime)) {
              loopRefresher(true);
            } else {
              loopRefresher();
            }
          });
      })
  }
};